<template>
  <div id="user" class="manage-pos">
    <tag-box v-show="showChild">
      <template v-slot:department>
        <div class="opentype-tag choose-bg-tag">用户-合同部门</div>
      </template>
    </tag-box>
    <div class="dep_top" v-show="!showChild">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="员工">
                <a-select show-search :filter-option="filterOption" v-model="queryParam.userId" placeholder="请选择员工">
                  <a-select-option
                    v-for="(item, index) in employeesList"
                    :value="item.id"
                    :title="item.userName"
                    :key="index">{{ item.userName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-edit-submitButtons">
                <a-button type="primary" class="ml8" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button class="ml8" @click="handleReset">重置</a-button>
                <a-button type="danger" class="ml8" @click="newHandler">新增</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <div class="dep_main" v-show="!showChild">
      <s-table
        ref="table"
        size="default"
        :row-key="(r,i) => i.toString()"
        :columns="columns"
        :data="loadData">
        <div slot="depList" slot-scope="text, record">
          <a-tag color="purple" v-if="record.depList.length > 0" v-for="(item, index) in record.depList" :key="index">{{ item.itemDesc }}</a-tag>
          <span v-if="record.depList.length === 0">--</span>
        </div>
        <span slot="action" slot-scope="t, r">
          <a href="javascript:void(0);" @click="editHandler(r)">编辑</a>
          <a-divider type="vertical" />
          <a href="javascript:void(0);" @click="delHandler(r)">删除</a>
        </span>
      </s-table>
    </div>
    <transition name="slide-fade">
      <div class="popContainer" v-if="showChild">
        <div class="box_container">
          <a-form
            :form="form"
            :label-col="{span: 4, offset: 1}"
            :wrapper-col="{span: 18}"
          >
            <a-form-item
              style="display: none"
            >
              <a-input
                v-decorator="['id']"
              />
            </a-form-item>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="员工">
                  <a-select
                    show-search
                    :filter-option="filterOption"
                    :disabled="editType===1"
                    v-decorator="['userId', validatorRules.userId]"
                    placeholder="请选择员工">
                    <a-select-option
                      v-for="(item, index) in employeesList"
                      :value="item.id"
                      :title="item.userName"
                      :key="index">{{ item.userName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item
                  label="部门">
                  <a-select
                    show-search
                    :filter-option="filterOption"
                    mode="multiple"
                    v-decorator="['depList', validatorRules.depIds]"
                    placeholder="请选择可查看的合同部门">
                    <a-select-option
                      v-for="dep in depList"
                      :key="dep.itemVal"
                      :value="dep.itemVal"
                      :title="dep.itemDesc"
                    >{{ dep.itemDesc }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="8" :sm="24">
                <span class="table-edit-submitButtons">
                  <a-button type="primary" class="ml8" :loading="saveLoading" @click="saveHandler()">保存</a-button>
                  <a-button class="ml8" @click="cancelHandler()">取消</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
    </transition>
  </div>
</template>
<script>
import { TagBox } from '@/myComponents'
import { STable } from '@/components'
import * as codeApi from '@/api/common'
import * as api from '@/api/systemAdmin'
import pick from 'lodash.pick'

export default {
  name: 'User',
  components: {
    STable,
    TagBox
  },
  data () {
    return {
      form: this.$form.createForm(this),
      loading: false,
      showChild: false,
      saveLoading: false,
      editType: 0, // 1:编辑状态
      employeesList: [],
      depList: [],
      columns: [
        {
          title: '序号',
          width: 50,
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          customRender: (t, r, index) => {
            return ((this.paginationInfo.pageNum - 1) * this.paginationInfo.pageSize + index + 1)
          }
        },
        {
          title: '员工',
          width: 90,
          align: 'center',
          dataIndex: 'userName'
        },
        {
          title: '合同部门',
          width: 90,
          align: 'center',
          scopedSlots: { customRender: 'depList' }
        },
        {
          title: '操作',
          width: 90,
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      queryParam: {},
      paginationInfo: null,
      loadData: parameter => {
        this.paginationInfo = parameter
        return api.getUserConDep(Object.assign(parameter, this.queryParam))
          .then(res => {
            if (res.code === 200) {
              return res.result
            } else if (res.code === 500) {
              this.$message.error('查询失败，' + res.msg)
              return {
                list: []
              }
            }
          })
      },
      validatorRules: {
        userId: { rules: [{ required: true, message: '请选择员工' }] },
        depIds: { rules: [{ required: true, message: '请选择可查看的合同部门' }] }
      }
    }
  },
  computed: {
  },
  beforeCreate () {
    api.getUserInfoForConDep({}).then(res => {
      this.employeesList = res.result
    })
    codeApi.LasCodeItem({ itemTypeId: 101 }).then(res => {
      this.depList = res.result
      console.log('this.depList', this.depList)
    })
  },
  created () {
  },
  mounted () {
  },
  methods: {
    handleReset () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    newHandler () {
      this.showChild = true
    },
    editHandler (record) {
      this.showChild = true
      this.editType = 1
      this.$nextTick(() => {
        const arr = record.depList.map(v => v.itemVal)
        this.form.setFieldsValue(pick(record, ['id', 'userId']))
        this.form.setFieldsValue({
          'depList': arr
        })
      })
    },
    delHandler (record) {
      const _this = this
      this.$confirm({
        title: '确定删除该条记录么',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          api.delUserConDep({ userId: record.userId }).then(res => {
            if (res.code === 200) {
              if (res.msg.indexOf('成功') >= 0) {
                _this.$message.success('删除成功！')
                _this.$refs.table.refresh(true)
              } else {
                _this.$message.error('删除失败！' + res.msg)
              }
            } else {
              _this.$message.error('服务出错' + res.msg)
            }
          })
        },
        onCancel () {
        }
      })
    },
    saveHandler () {
      this.saveLoading = true
      this.form.validateFields((err, values) => {
        if (err == null) {
          setTimeout(() => {
            console.log('保存的数据', values)
            api.saveUserConDep(values).then(res => {
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  this.$message.success('保存成功！')
                  this.$refs.table.refresh(true)
                  this.showChild = false
                  this.editType = 0
                  this.saveLoading = false
                } else {
                  this.$message.error('保存失败！' + res.msg)
                  this.saveLoading = false
                }
              } else {
                this.$message.error(res.msg)
                this.saveLoading = false
              }
            }).catch(e => {
              this.$message.error('保存失败！')
              this.saveLoading = false
              console.error(e)
            })
          }, 2000)
        } else {
          this.$message.error('存在非法输入！')
          this.saveLoading = false
        }
      })
    },
    cancelHandler () {
      this.showChild = false
      this.editType = 0
    },
    filterOption (input, option) {
      return option.componentOptions.propsData['title'].indexOf(input) >= 0
    }
  }
}
</script>
<style scoped>

</style>
